<template>
	<view @click="showPicker">
		<slot></slot>

		<u-popup :show="show" mode="bottom" @touchmove.stop.prevent="moveHandle" :safeAreaInsetBottom="false"
			bgColor="transparent">
			<view class="popup">
				<view class="top_nav flex-box">
					<view class="flex-grow-1">{{title}}</view>
					<image @click="close" src="https://admin.mosizp.cn/static/public/pop_close.png" mode="aspectFill" class="ico44"></image>
				</view>
				<view class="flex" v-show="max==1">
					<scroll-view scroll-y="true" class="main_scroll" :scroll-into-view="intoView1"
						scroll-with-animation="true">
						<view class="item m-ellipsis" @click="bindOnlyChange(index)" :class="{active: mainindex==index}"
							:key="item[id_key]" :id="'main' + index" v-for="(item,index) in items">{{item[name_key]}}
						</view>

					</scroll-view>
				</view>
				<view class="flex" v-show="max==2">
					<scroll-view scroll-y="true" class="left_scroll" :scroll-into-view="intoView1">
						<view class="item m-ellipsis" @click="bindMainChange(index)" :class="{active: mainindex==index}"
							:key="item[id_key]" :id="'main' + index" v-for="(item,index) in items">{{item[name_key]}}
						</view>

					</scroll-view>
					<scroll-view scroll-y="true" class="flex-grow-1 right_scroll" :scroll-into-view="intoView2">
						<view class="item m-ellipsis" :class="{active: streetIndex==index}"
							@click="bindStreetChange(index)" :key="item[id_key]" :id="'street' + index"
							v-for="(item,index) in (items[mainindex] && items[mainindex][children_key] ? items[mainindex][children_key] : [])">{{item[name_key]}}</view>
					</scroll-view>
				</view>
				<view class="flex" v-show="max==3">
					<scroll-view scroll-y="true" class="left_scroll flex-grow-1" :scroll-into-view="intoView1">
						<view class="item m-ellipsis" @click="bindMainChange(index)" :class="{active: mainindex==index}"
							:key="item[id_key]" :id="'main' + index" v-for="(item,index) in items">{{item[name_key]}}
						</view>

					</scroll-view>
					<scroll-view scroll-y="true" class="flex-grow-1 right_scroll" :scroll-into-view="intoView2">
						<view class="item m-ellipsis" :class="{active: streetIndex==index}"
							@click="bindStreetChange3(index)" :key="item[id_key]" :id="'street' + index"
							v-for="(item,index) in (items[mainindex] && items[mainindex][children_key] ? items[mainindex][children_key] : [])">{{item[name_key]}}</view>
					</scroll-view>
					<scroll-view scroll-y="true" class="flex-grow-1 rd right_scroll" :scroll-into-view="intoView3">
						<view class="item m-ellipsis" :class="{active: rdIndex==index}"
							@click="bindStreet2Change3(index)" :key="item[id_key]" :id="'rd' + index"
							v-for="(item,index) in (items[mainindex] && items[mainindex][children_key] && items[mainindex][children_key][streetIndex] && items[mainindex][children_key][streetIndex][children_key] ? items[mainindex][children_key][streetIndex][children_key] : [])">
							{{item[name_key]}}
						</view>
					</scroll-view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	export default {
		name: "multi-select",
		data() {
			return {

				show: false,
				mainindex: 0,
				streetIndex: 0,
				rdIndex: 0,
				//picker's range property
				range: [],
				//每列选中的index
				indexValues: [],
				intoView1: "",
				intoView2: "",
				intoView3: "",
				max: 3,
			};
		},
		props: {
			// 嵌套数据 [obj,obj,obj] ; obj={id:xx,name:xx,children:[obj,obj]}
			title: {
				type: String,
				default: '请选择'
			},
			items: {
				type: Array,
				default: () => [],
			},
			// 主键字段名
			id_key: {
				type: String,
				default: "id",
			},
			// 显示字段名
			name_key: {
				type: String,
				default: "name",
			},
			// 子列表字段名
			children_key: {
				type: String,
				default: "children",
			},
			// 最大层数
			max_level: {
				type: Number,
				default: 3,
			},
			// 选中的最后一层obj.id, 以渲染picker的index
			value: {
				type: Number,
				default: null,
			},

		},
		watch: {
			items: {
				immediate: true,
				handler(newItems) {
					
					if (newItems.length > 0 && this.value !== null && this.value != 0) {
						const indexes = this.findIndexesByValue();
						this.mainindex = indexes[0];
						if (indexes.length >= 2) this.streetIndex = indexes[1];
						if (indexes.length >= 3) this.rdIndex = indexes[2];
						this.$nextTick(() => {
							this.tabsChange(); // 确保DOM更新后滚动到正确位置
							this.emitInitialValue();
						});
					}
				}
			},
			value(newVal, oldVal) {
				if (newVal == null || newVal == -1) {
					return
				} else if (newVal != null && newVal != -1) {
					const indexes = this.findIndexesByValue();
					if(indexes!=null){
						this.mainindex = indexes[0];
						if (indexes.length >= 2) this.streetIndex = indexes[1];
						if (indexes.length >= 3) this.rdIndex = indexes[2];
						this.$nextTick(() => {
							this.tabsChange(); // 确保DOM更新后滚动到正确位置
							this.emitInitialValue();
						});
					}
					
				}
			},
			show(newValue, oldValue) {
				if (newValue !== oldValue) {

					this.tabsChange()
					const calculateMaxLevel = (items, currentLevel = 1) => {
						if (!items || items.length === 0) return currentLevel;
						const nextLevel = items[0][this.children_key]?.length > 0 ? currentLevel + 1 : currentLevel;
						return calculateMaxLevel(items[0][this.children_key], nextLevel);
					};
					this.max = Math.min(this.max_level, calculateMaxLevel(this.items));

				}

			},

		},
		created() {
			this.show1 = true
			this.tabsChange()
		},
		methods: {
			moveHandle() {},
			tabsChange() {
				setTimeout(() => {
					this.$nextTick(() => {
						this.intoView1 = "main" + this.mainindex;
						this.intoView2 = "street" + this.streetIndex;
						this.intoView3 = "rd" + this.rdIndex
					});

				}, 1500)

			},
			showPicker() {
				if (!this.items || this.items.length === 0) return;
				this.show = true;
			},
			close() {
				this.show = false;
			},
			bindMainChange(index) {
				this.mainindex = index
			},
			bindStreetChange(index) {
				this.streetIndex = index;
				let m = this.items[this.mainindex];
				if (!m || !m[this.children_key]) return;
				let n = m[this.children_key][this.streetIndex];
				let indexValues = [this.mainindex, this.streetIndex]
				let items = [m, n];
				this.$emit("change", {
					items,
					indexValues
				});
				this.show = false
			},
			bindOnlyChange(index) {
				this.mainindex = index;
				this.streetIndex = 0;
				let indexValues = [this.mainindex]
				let i = this.items[this.mainindex];
				let items = [i]
				this.$emit("change", {
					items,
					indexValues
				});
				this.show = false
			},
			bindStreetChange3(index) {
				this.streetIndex = index;
			},
			bindStreet2Change3(index) {
				this.rdIndex = index;
				let m = this.items[this.mainindex];
				if (!m || !m[this.children_key]) return;
				let n = m[this.children_key][this.streetIndex];
				if (!n || !n[this.children_key]) return;
				let t = n[this.children_key][this.rdIndex]
				let indexValues = [this.mainindex, this.streetIndex, this.rdIndex]
				let items = [m, n, t];
				this.$emit("change", {
					items,
					indexValues
				});
				this.show = false
			},
			// 根据value查找各层级索引
			findIndexesByValue() {
				const traverse = (items, targetId, depth = 0, path = []) => {
					for (let i = 0; i < items.length; i++) {
						const item = items[i];
						if (item[this.id_key] === targetId) {
							return [...path, i]; // 返回索引数组 [mainindex, streetIndex, rdIndex]
						}
						if (item[this.children_key]?.length > 0 && depth < this.max_level - 1) {
							const result = traverse(item[this.children_key], targetId, depth + 1, [...path, i]);
							if (result) return result;
						}
					}
					return null;
				};
				// console.log(this.items, this.value);
				return traverse(this.items, this.value) || null; // 找不到则默认选中首项
			},
			// 构造初始值并触发事件
			emitInitialValue() {
				let items = [];
				let indexValues = [];

				// 根据层级构造数据
				if (this.max >= 1 && this.items.length > 0) {
					const mainItem = this.items[this.mainindex];
					if (!mainItem) return;
					items.push(mainItem);
					indexValues.push(this.mainindex);

					if (this.max >= 2 && mainItem[this.children_key]?.length > 0) {
						const streetItem = mainItem[this.children_key][this.streetIndex];
						if (!streetItem) return;
						items.push(streetItem);
						indexValues.push(this.streetIndex);

						if (this.max >= 3 && streetItem[this.children_key]?.length > 0) {
							const rdItem = streetItem[this.children_key][this.rdIndex];
							if (!rdItem) return;
							items.push(rdItem);
							indexValues.push(this.rdIndex);
						}
					}
				}
				// 触发事件
				this.$emit("change", {
					items,
					indexValues
				});
			}
		},
	};
</script>

<style lang="scss" scoped>
	.popup {
		background: #fff;

		.top_nav {
			height: 110rpx;
			padding: 0 30rpx;
			font-size: 35rpx;
			color: #333333;
			font-weight: bold;
			border-bottom: 1px solid var(--primary1);
		}

		.left_scroll,
		.right_scroll {
			height: 70vh;
		}

		.right_scroll.rd {
			background: rgba(216, 216, 216, 0.2);
		}

		.main_scroll {
			min-height: 30vh;
			max-height: 70vh;
			width: 100%;

			.item {
				height: 100rpx;
				text-align: center;
				width: 100%;
				line-height: 100rpx;
				color: #333333;
				font-size: 26rpx;
			}

			.item.active {
				background: var(--primary1);
				border: 1rpx solid rgba(151, 151, 151, .1);
				color: var(--primary);
			}
		}

		.left_scroll {
			background: rgba(216, 216, 216, 0.2);
			width: 267rpx;

		}

		.item {
			width: 100%;
			height: 104rpx;
			line-height: 104rpx;
			color: #333333;
			font-size: 26rpx;
			padding: 0 30rpx;
		}

		.item.active {
			background: #fff;
			color: var(--primary);
		}
	}
</style>